$(function () {
    obj.init();
});

window.obj = new function() {
    'use strict';
    return {
        dataGrid: null,
        classGrid: null,
        params: {
            schoolId: null,
            userType: 1
        },
        allowEdit: false,
        editIndex: undefined,
        authStuds: [],
        init: function () {
            window.top.swal.resetDefaults();
            this.params.schoolId = xhTool.getQuery('iSchoolId');
            this.classGrid = new xhDataGrid($('#class_list'), 'School/getAdClass', {schoolId: this.params.schoolId});
            this.classGrid.init();

            this.dataGrid = new xhDataGrid($('#list'), 'School/getUser', {schoolId: this.params.schoolId, userType: this.params.userType, ebook: 1});
            this.dataGrid.parseToolbar().init()
                .activeBtn(
                    $('#bt_list_set_pwd, #bt_list_unbind_device, #bt_list_refresh_login, #bt_list_set_class, #bt_list_auth,#bt_list_returnTab, #bt_list_bindLicence'),
                    $('#bt_list_app_group, #bt_list_assist, #bt_list_login, #bt_list_bind' )
                );

            $('#bt_list_tablet').menubutton({
                menu: '#menu_tablet'
            });
            $('#bt_list_apply').menubutton({
                menu: '#menu_apply'
            });
            $('#bt_list_setting').menubutton({
                menu: '#menu_setting'
            });
            $('#bt_list_import').menubutton({
                menu: '#menu_import'
            });
            $('#bt_list_more').menubutton({
                menu: '#menu_more'
            });
            $('#bt_account_use').menubutton({
                menu: '#menu_use_type'
            });
            //
            // $('#bt_list_spare').menubutton({
            //     menu: '#menu_spare'
            // });
            // $('#bt_list_borrow').menubutton({
            //     menu: '#menu_borrow'
            // });
            // $('#bt_list_status').menubutton({
            //     menu: '#menu_status'
            // });
            // $('#bt_list_ebook').menubutton({
            //     menu: '#menu_ebook'
            // });
            // $('#bt_list_dev').menubutton({
            //     menu: '#menu_dev'
            // });
            // // $('#bt_list_poor').menubutton({
            // //     menu: '#menu_poor'
            // // });
            // $('#bt_list_attr').menubutton({
            //     menu: '#menu_attr'
            // });
            // $('#bt_list_repair').menubutton({
            //     menu: '#menu_repair'
            // });

            this.listener();
        },
        listener: function () {
            var $this = this;
            //处理列表事件
            // $this.dataGrid.rowStyler = function(rowIndex, rowData){
            //     if (rowData.bDisable === '是'){
            //         return 'background-color:yellow;';
            //     }
            // };
            $this.classGrid.onChangeCheck($this.funObj().search);
            $this.dataGrid.onLoadSuccess = function(data){
                //add by sqb 2018/12/13    异步加载登录数据
                if (this.params.userType == 1) {
                    var rows = $this.dataGrid.command('getRows');
                    $.each(rows, function (index, row) {
                        $this.dataGrid.command('updateRow', {index: index, row: {
                            loginCount: '<i class="fa fa-spinner fa-spin"></i>',
                            lastLoginDate: '<i class="fa fa-spinner fa-spin"></i>'
                        }});
                    });
                    xhExtra.ajaxRequest('school/getUserLoginInfo', {rows: rows}, {}, function (data) {
                        if (data) {
                            for (var index in rows) {
                                index = parseInt(index);
                                $this.dataGrid.command('updateRow', {
                                    index: index,
                                    row: {
                                        loginCount: data[index].loginCount,
                                        lastLoginDate: data[index].lastLoginDate,
                                        sUserName: data[index].sUserName
                                    }
                                });

                                if (isNaN(data[index].loginCount)) {
                                    $this.dataGrid.command('updateRow', {index: index, row: {
                                        loginCount: '',
                                    }});
                                }

                                var lastLoginDate = data[index].lastLoginDate.replace(/-/g, '/');
                                lastLoginDate = Date.parse(lastLoginDate);
                                if (isNaN(lastLoginDate)) {
                                    $this.dataGrid.command('updateRow', {index: index, row: {
                                        lastLoginDate: ''
                                    }});
                                }
                            }
                        }
                    });
                }
                //end add

                xhExtra.checkError(data);
                $this.dataGrid.clear();
                $this.authStuds = [];
                // $('.showFileTable').click(function () {
                //     var iUserId = $(this).attr('id');
                //     $this.funObj().showFileTable(iUserId);
                // });
            };
            //双击更改学号
            $this.dataGrid.onDblClickCell = function(rowIndex, field, value){
                if (field !== 'studentNo' || !$this.allowEdit || !$this.funObj().endEditing()) {
                    return false;
                }
                $this.dataGrid.command('beginEdit', rowIndex);
                var ed = $this.dataGrid.command('getEditor', {index: rowIndex, field: 'studentNo'});
                $(ed.target).next().children().focus();
                $this.editIndex = rowIndex;
            };
            $this.dataGrid.onClickRow = function (rowIndex, rowData) {
                $this.funObj().endEditing();
            };
            //绑定搜索事件
            xhTool.bindDocKeyDown(
                $('#bt_list_search').click(function(){
                    $this.funObj().search();
                })
            );
            //解除设备绑定
            // $('#bt_list_unbind_device').click(function(){
            //     if(xhExtra.buttonDisabled($(this))) return false;
            //     $this.funObj().unbindDevice(1);
            // });
            //刷新登陆
            $('#bt_list_refresh_login').click(function(){
                if(xhExtra.buttonDisabled($(this))) return false;
                $this.funObj().refreshLogin();
            });

            // //查看应用组
            // $('#bt_list_app_group').click(function () {
            //     if(xhExtra.buttonDisabled($(this))) return false;
            //     $this.funObj().viewAppGroup();
            // });
            //修改密码
            $('#bt_list_set_pwd').click(function () {
                if(xhExtra.buttonDisabled($(this))) return false;
                $this.funObj().setUserPwd();
            });
            //归还备用机
            // $('#bt_list_return_spare').click(function () {
            //     if(xhExtra.buttonDisabled($(this))) return false;
            //     $this.funObj().doneSpareUsed();
            // });
            // //使用备用机
            // $('#bt_list_set_spare').click(function () {
            //     if(xhExtra.buttonDisabled($(this))) return false;
            //     $this.funObj().openSpareList();
            // });
            //设为历史
            // $('#bt_list_set_history').click(function () {
            //     if(xhExtra.buttonDisabled($(this))) return false;
            //     $this.funObj().setHistory(true);
            // });
            // //设为正常
            // $('#bt_list_set_normal').click(function () {
            //     if(xhExtra.buttonDisabled($(this))) return false;
            //     $this.funObj().setHistory(false);
            // });
            //设置班级
            // $('#bt_list_set_class').click(function () {
            //     if(xhExtra.buttonDisabled($(this))) return false;
            //     $this.funObj().setClassName();
            // });
            //导出
            $('#bt_list_export').click(function () {
                $this.funObj().exportTablet();
            });
            //编辑学号
            $('#bt_list_set_studentNo').click(function () {
                $this.allowEdit = $(this).find('i').hasClass('fa-pencil');
                if ($(this).html().indexOf('编辑序号') >= 0) {
                    $(this).html($(this).html().replace('编辑序号', '提交编辑'));
                }
                else {
                    $(this).html($(this).html().replace('提交编辑', '编辑序号'));
                    $this.funObj().submitEdit();
                }
                $(this).find('i').toggleClass('fa-pencil fa-check');
            });
            //借用平板
            // $('#bt_list_set_borrow').click(function () {
            //     if(xhExtra.buttonDisabled($(this))) return false;
            //     $this.funObj().openBorrowPage();
            // });
            // //归还平板
            // $('#bt_list_return_borrow').click(function () {
            //     if(xhExtra.buttonDisabled($(this))) return false;
            //     $this.funObj().unbindDevice(2);
            // });
            //远程协助
            // $('#bt_list_assist').click(function() {
            //     if(xhExtra.buttonDisabled($(this))) return false;
            //     $this.funObj().startAssist();
            // });
            // //导入身份证
            // $('#bt_list_import_identity').click(function() {
            //     $this.funObj().importIdentity();
            // });
            // //导入序号
            // $('#bt_list_import_studentNo').click(function() {
            //     $this.funObj().importStudentNo();
            // });
            // //认证
            // $('#bt_list_auth').click(function () {
            //     if(xhExtra.buttonDisabled($(this))) return false;
            //     $this.funObj().authStudTablet();
            // });
            // //导入学生
            // $('#bt_list_import').click(function () {
            //     $this.funObj().importStudent();
            // });
            //扫码登陆
            $('#bt_list_login').click(function () {
                if(xhExtra.buttonDisabled($(this))) return false;
                $this.funObj().scanLogin();
            });
            // //添加绑定
            // $('#bt_list_bind').click(function() {
            //     $this.funObj().addBindTablet();
            // });
            //设备归还
            $("#bt_list_returnTab").click(function () {
                $this.funObj().returnTab();
            });
            $('#bt_list_payVoucher').click(function () {
                $this.funObj().uploadPayVoucher();
            });
            $("#bt_list_checkPayVoucher").click(function () {
                $this.funObj().showPayVoucher();
            });
            $('#bt_list_bindLicence').click(function () {
                if(xhExtra.buttonDisabled($(this))) return false;
                $this.funObj().bindLicence();
            });

        },
        funObj: function () {
            var $this = this;
            return {
                search: function (_return) {
                    var params = {
                        search: {
                            vague: xhExtra.getValue($('#list_vague')),
                            items: xhExtra.getValue($('#list_items'))
                        },
                        history: xhExtra.getValue($('#list_history')),
                        cost: xhExtra.getValue($('#list_cost')),
                        ebook: xhExtra.getValue($('#list_ebook')),
                        chargeYear: xhExtra.getValue($('#list_cost_year')),
                        createStart: xhExtra.getValue($('#list_create_start')),
                        createEnd: xhExtra.getValue($('#list_create_end')),
                        devSource: xhExtra.getValue($('#list_dev')),
                        payStatus: xhExtra.getValue($('#list_payVoucher_status'))
                    };
                    var classNames = $this.classGrid.getSelectValues('classNames');
                    if (classNames.length > 0) {
                        params.classNames = classNames.join(',');
                    }
                    if (_return) {
                        params.userIds = $this.dataGrid.getSelectValues('iUserId');
                    }
                    $this.dataGrid.reload(params);
                    if (_return) {
                        return params;
                    }
                },
                unbindDevice: function (type) {
                    var bindIds = xhTool.clearNullArr($this.dataGrid.getSelectValues('iADLId'));
                    if(bindIds.length <= 0){
                        window.top.xhTop.showMessage({type: 'error', title: '未选中需解绑记录！'});
                        return false;
                    }
                    xhExtra.askChangeStatus('Device/unbindBound', {ids: bindIds, type: type}, $this.dataGrid, type === 2 ? '确认归还？' : '确认解绑？');
                },
                refreshLogin: function () {
                    xhExtra.ajaxRequest('School/refreshLoginInfo', {userIds: $this.dataGrid.getSelectValues('iUserId')}, {success: true, table: $this.dataGrid});
                },
                viewAppGroup: function () {
                    var userId = $this.dataGrid.getSelectValue('iUserId');
                    if (!userId) {
                        window.top.xhTop.showError('未选中学生！');
                        return false;
                    }
                    window.top.xhTop.createNewTab(
                        '应用组-' + $this.dataGrid.getSelectValue('sUserName'),
                        baseUrl + 'Appgroup/appGroup?' + xhTool.parseParam({schoolId: $this.params.schoolId, userId: userId}),
                        true
                    );
                },
                setUserPwd: function () {
                    window.top.swal({
                        showCancelButton: true,
                        confirmButtonText: '修改',
                        cancelButtonText: '取消',
                        showLoaderOnConfirm: true,
                        allowOutsideClick: false,
                        title: '输入新密码',
                        html: '<input type="password" id="new_pwd" class="swal2-input" placeholder="新密码" />' +
                        '<input type="password" id="confirm_pwd" class="swal2-input" placeholder="确认密码" >' +
                        '学生补全：<select id="reset_omplete" class="swal2-select"><option value="0">否</option><option value="1">是</option></select>',
                        preConfirm: function() {
                            return new Promise(function (resolve, reject) {
                                var newPwd     = $('#new_pwd', window.top.document).val(),
                                    confirmPwd = $('#confirm_pwd', window.top.document).val(),
                                    resetComplete = $('#reset_omplete', window.top.document).val();
                                if(newPwd.length < 6){
                                    reject('密码需大于6位数！');
                                } else if (newPwd !== confirmPwd) {
                                    reject('密码不匹配！');
                                } else {
                                    xhExtra.ajaxRequest(
                                        'User/setPassword',
                                        {userIds: $this.dataGrid.getSelectValues('iUserId'), password: newPwd, resetComplete: resetComplete},
                                        {success: true}
                                    );
                                    resolve();
                                }
                            })
                        }
                    })
                },
                doneSpareUsed: function () {
                    var ids = xhTool.clearNullArr($this.dataGrid.getSelectValues('iUTId'));
                    if (ids.length < 1) {
                        window.top.xhTop.showError('无备用机使用！');
                        return false;
                    }
                    xhExtra.askChangeStatus(
                        'Device/doneRegister',
                        {ids: ids},
                        $this.dataGrid,
                        '归还备用机？'
                    );
                },
                openSpareList: function () {
                    var row = $this.dataGrid.getSelectValue(true);
                    if (!row) {
                        window.top.xhTop.showError('未选中记录！');
                        return false;
                    }
                    if (row.iUTId) {
                        window.top.xhTop.showError('已使用备用机！', '请归还后重试！');
                        return false;
                    }
                    window.top.xhTop.showModal({
                        title: '使用备用机-' + row.sUserName,
                        size: 'lg',
                        button: '确认',
                        content: xhTool.getFrameString('Device/spareRegister', {logonName: row.sLogonName}, 500)
                    });
                },
                setHistory: function (history) {
                    var ids = $this.dataGrid.getSelectValues('iUserId');
                    if (ids.length <= 0) {
                        window.top.xhTop.showError('未选中记录！');
                        return false;
                    }
                    if (history) {
                        window.top.swal({
                            title: '选择历史类型',
                            input: 'select',
                            inputOptions: {
                                0: '--选择历史类型--',
                                1: '转校',
                                2: '毕业',
                                3: '退用'
                            },
                            showCancelButton: true,
                            confirmButtonText: '确认',
                            cancelButtonText: '取消',
                            showLoaderOnConfirm: true,
                            allowOutsideClick: false,
                            preConfirm: function(type) {
                                return new Promise(function (resolve, reject) {
                                    if(type == 0){
                                        reject('请先选择类型！');
                                    }
                                    else {
                                        xhExtra.ajaxRequest(
                                            'User/setHistory',
                                            {ids: ids, history: history, type: type},
                                            {success: true, table: $this.dataGrid},
                                            function () {
                                                $this.classGrid.reload();
                                            }
                                        );
                                        resolve();
                                    }
                                })
                            }
                        }).then(function(isConfirm) {}, function(dismiss) {});
                    } else {
                        xhExtra.askChangeStatus('User/setHistory', {ids: ids, history: history}, $this.dataGrid, '设置为正常？');
                    }

                },
                setClassName: function () {
                    var ids = $this.dataGrid.getSelectValues('iUserId');
                    if (ids.length <= 0) {
                        window.top.xhTop.showError('未选中用户');
                        return false;
                    }
                    window.top.swal({
                        title: '设置班级名称',
                        input: 'text',
                        showCancelButton: true,
                        confirmButtonText: '确认',
                        cancelButtonText: '取消',
                        showLoaderOnConfirm: true,
                        allowOutsideClick: false,
                        preConfirm: function(className) {
                            return new Promise(function (resolve, reject) {
                                if(!className){
                                    reject('班级名不能为空！');
                                }
                                else {
                                    xhExtra.ajaxRequest(
                                        'School/setClassName',
                                        {ids: ids, className: className, schoolId: $this.params.schoolId},
                                        {success: true, table: $this.dataGrid},
                                        function () {
                                            $this.classGrid.reload();
                                        }
                                    );
                                    resolve();
                                }
                            })
                        }
                    }).then(function(isConfirm) {}, function(dismiss) {});
                },
                endEditing: function () {
                    if ($this.editIndex === undefined) {
                        return true
                    }
                    if ($this.dataGrid.command('validateRow', $this.editIndex)) {
                        $this.dataGrid.command('endEdit', $this.editIndex);
                        $this.editIndex = undefined;
                        return true;
                    }
                    return false;
                    // for (var i = 0; i < $this.dataGrid.command('getRows').length; i++) {
                    //     obj.dataGrid.command('beginEdit', i);
                    // }
                    // obj.dataGrid.list.datagrid('beginEdit', 5);
                    // obj.dataGrid.list.datagrid('endEdit', 5);
                    // obj.dataGrid.list.datagrid('getChanges');//rows
                },
                submitEdit: function () {
                    $this.funObj().endEditing();
                    var changes = $this.dataGrid.command('getChanges');
                    if (changes.length <= 0) {
                        window.top.xhTop.showSuccess('未修改，无需提交！');
                        return false;
                    }
                    var updateInfo = [];
                    $.each(changes, function (index, row){
                        updateInfo.push({studentId: row.iUserId, studentNo: row.studentNo});
                    });
                    xhExtra.askChangeStatus('School/updateStudentNo', {schoolId: $this.params.schoolId, info: updateInfo}, $this.dataGrid, '提交学号更改？');
                },
                openBorrowPage: function () {
                    var row = $this.dataGrid.getSelectValue(true);
                    if (!row) {
                        window.top.xhTop.showError('未选中记录！');
                        return false;
                    }
                    if (row.iUTId) {
                        window.top.xhTop.showError('不可借用', '该学生正使用备用机！');
                        return false;
                    }
                    window.top.xhTop.showModal({
                        title: '平板借用-' + row.sUserName,
                        content: xhTool.getFrameString('School/studBorrowTablet', {userId: row.iUserId, schoolId: $this.params.schoolId}, 500),
                        button: '借用',
                        size: 'lg'
                    });
                },
                setEbook: function (used) {
                    var ids = $this.dataGrid.getSelectValues('iUserId');
                    if (ids.length <= 0) {
                        window.top.xhTop.showError('未选中记录！');
                        return false;
                    }
                    xhExtra.askChangeStatus('School/setEbookStatus', {ids: ids, used: used}, $this.dataGrid, used ? '使用电子书包？' : '取消使用？');
                },
                startAssist: function () {
                    var id = $this.dataGrid.getSelectValue('iUserId');
                    if (!id) {
                        window.top.xhTop.showError('未选中记录！');
                        return false;
                    }
                    window.top.xhTop.createNewTab($this.dataGrid.getSelectValue('sUserName') + '-客户端列表', baseUrl + 'assist/users/clients?id=' + id);
                },
                setDevSource: function (source) {
                    var ids = $this.dataGrid.getSelectValues('iUserId');
                    if (ids.length <= 0) {
                        window.top.xhTop.showError('未选中记录！');
                        return false;
                    }
                    // xhExtra.askChangeStatus('School/setDevSource', {ids: ids, source: source}, $this.dataGrid, '确认修改？');
                    window.top.swal({
                        input: 'text',
                        inputPlaceholder: '备注',
                        showConfirmButton: true,
                        confirmButtonText: '确定',
                        showCancelButton: true,
                        cancelButtonText: '取消',
                        preConfirm: function () {
                            return new Promise(function (resolve, reject) {
                                resolve();
                            })
                        }
                    }).then(function (comment) {
                        xhExtra.ajaxRequest('school/setDevSource', {ids: ids, comment: comment, source: source}, {success: true, check: true, table: $this.dataGrid});
                    }, function (dismiss) {});
                },
                setPoorLevel: function (level) {
                    var ids = $this.dataGrid.getSelectValues('iUserId');
                    if (ids.length <= 0) {
                        window.top.xhTop.showError('未选中记录！');
                        return false;
                    }
                    xhExtra.askChangeStatus('School/setPoorLevel', {ids: ids, level: level}, $this.dataGrid, '确认修改等级？');
                },
                importIdentity: function () {
                    window.top.swal({
                        title: '导入excel文件',
                        showCancelButton: true,
                        cancelButtonText: '取消',
                        showLoaderOnConfirm: true,
                        allowOutsideClick: true,
                        input: 'file',
                        inputAttributes: {accept: '.xls,.xlsx'},
                        confirmButtonText: '导入',
                        preConfirm: function(file) {
                            return new Promise(function (resolve, reject) {
                                if (!file) {
                                    reject('文件不能为空！');
                                } else {
                                    var fileData = new FormData();
                                    fileData.append('file', file);
                                    fileData.append('schoolId', $this.params.schoolId);
                                    $.ajax({
                                        url: baseUrl + 'School/importStudIdentity',
                                        type: 'POST',
                                        processData: false,
                                        contentType: false,
                                        data: fileData,
                                        complete: function(XMLHttpRequest){
                                            var result = XMLHttpRequest.responseJSON;
                                            if(xhExtra.checkError(result)) return false;
                                            if (result.errorData.length > 0){
                                                var content = '';
                                                $.each(result.errorData, function(index, row){
                                                    content += '<tr><td>' + row.userName + '</td><td>' + row.logonName + '</td><td>' + row.reason + '</td></tr>';
                                                });
                                                window.top.swal({
                                                    title: result.msg,
                                                    type: 'warning',
                                                    html: '<table class="table table-striped"><tr>' +
                                                    '<th style="text-align: center">姓名</th>' +
                                                    '<th style="text-align: center">登录名</th>' +
                                                    '<th style="text-align: center">原因</th>' +
                                                    '</tr>' + content + '</table>'
                                                });
                                            }
                                            else{
                                                window.top.xhTop.showSuccess(result.msg);
                                            }
                                            $this.dataGrid.reload();
                                        }
                                    });
                                }
                            })
                        }
                    });//.then(function(result) {}, function(dismiss) {});
                },
                importStudentNo: function () {
                    window.top.swal({
                        title: '导入excel文件',
                        showCancelButton: true,
                        cancelButtonText: '取消',
                        showLoaderOnConfirm: true,
                        allowOutsideClick: true,
                        input: 'file',
                        inputAttributes: {accept: '.xls,.xlsx'},
                        confirmButtonText: '导入',
                        preConfirm: function(file) {
                            return new Promise(function (resolve, reject) {
                                if (!file) {
                                    reject('文件不能为空！');
                                } else {
                                    var fileData = new FormData();
                                    fileData.append('file', file);
                                    fileData.append('schoolId', $this.params.schoolId);
                                    $.ajax({
                                        url: baseUrl + 'School/importStudNo',
                                        type: 'POST',
                                        processData: false,
                                        contentType: false,
                                        data: fileData,
                                        complete: function(XMLHttpRequest){
                                            var result = XMLHttpRequest.responseJSON;
                                            if(xhExtra.checkError(result)) return false;
                                            if (result.errorData.length > 0){
                                                var content = '';
                                                $.each(result.errorData, function(index, row){
                                                    content += '<tr><td>' + row.userName + '</td><td>' + row.logonName + '</td><td>' + row.reason + '</td></tr>';
                                                });
                                                window.top.swal({
                                                    title: result.msg,
                                                    type: 'warning',
                                                    html: '<table class="table table-striped"><tr>' +
                                                    '<th style="text-align: center">姓名</th>' +
                                                    '<th style="text-align: center">登录名</th>' +
                                                    '<th style="text-align: center">原因</th>' +
                                                    '</tr>' + content + '</table>'
                                                });
                                            }
                                            else{
                                                window.top.xhTop.showSuccess(result.msg);
                                            }
                                            $this.dataGrid.reload();
                                        }
                                    });
                                }
                            })
                        }
                    });
                },
                setTchChild: function (level) {
                    var ids = $this.dataGrid.getSelectValues('iUserId');
                    if (ids.length <= 0) {
                        window.top.xhTop.showError('未选中记录！');
                        return false;
                    }
                    if (level === 2) {
                        window.top.swal({
                            title: '输入教师子女信息',
                            confirmButtonText: '确认',
                            showCancelButton: true,
                            cancelButtonText: '取消',
                            showLoaderOnConfirm: true,
                            allowOutsideClick: false,
                            html: '<input id="devCost" class="swal2-input" placeholder="设备费(默认为0)" />' +
                            '<input id="serCost" class="swal2-input" placeholder="服务费(默认为0)" />',
                            preConfirm: function() {
                                return new Promise(function (resolve, reject) {
                                    var devCost   = $('#devCost', window.top.document).val(),
                                        serCost   = $('#serCost', window.top.document).val();
                                    xhExtra.ajaxRequest('School/setTchChild',
                                        {ids: ids, level: level, devCost: devCost, serCost: serCost},
                                        {success: true, table: $this.dataGrid}
                                    );
                                })
                            }
                        });
                    }
                    else {
                        xhExtra.askChangeStatus('School/setTchChild', {ids: ids, level: level}, $this.dataGrid, '确认修改？');
                    }
                },
                setBehind: function (behind) {
                    var ids = $this.dataGrid.getSelectValues('iUserId');
                    if (ids.length <= 0) {
                        window.top.xhTop.showError('未选中记录！');
                        return false;
                    }
                    xhExtra.askChangeStatus('School/setStudBehind', {ids: ids, behind: behind}, $this.dataGrid, '确认修改？');
                },
                exportTablet: function () {
                    window.top.swal({
                        title: '请选择导出类型',
                        text: '',
                        type: 'info',
                        showCancelButton: true,
                        confirmButtonText: '签收表',
                        cancelButtonText: 'MAC地址'
                    }).then(function() {
                        location.href = baseUrl + 'School/exportUserTablet?' + xhTool.parseParam($.extend({}, $this.funObj().search(true), $this.params));
                    }, function(dismiss) {
                        if (dismiss === 'cancel') {
                            location.href = baseUrl + 'School/exportUserTabletMac?' + xhTool.parseParam($.extend({}, $this.funObj().search(true), $this.params));
                        }
                    });
                },
                authStudTablet: function () {
                    $.extend($this.authStuds, $this.dataGrid.command('getSelections'));
                    // $this.authStuds = JSON.parse(JSON.stringify($this.dataGrid.command('getSelections')));
                    $this.funObj().showAuthQR();
                },
                showAuthQR: function () {
                    if ($this.authStuds.length <= 0) {
                        return false;
                    }
                    var showBtn = $this.authStuds.length > 1,
                        userId  = $this.authStuds[0].iUserId,
                        userName= $this.authStuds[0].sUserName;
                    $this.authStuds.splice(0, 1);
                    xhExtra.ajaxRequest('School/userAuthQR', {userId: userId, userType: 1}, {check: false}, function(result) {
                        window.top.swal({
                            title: '认证-' + userName,
                            // html: result.error || '<img src="data:image/png;base64,' + result.msg + '" width="80%">',
                            html: result.error || '<img src="' + result.msg + '" width="80%">',
                            showConfirmButton: showBtn,
                            showCancelButton: true,
                            confirmButtonText: '下一个',
                            cancelButtonText: '关闭'
                        }).then(function () {
                            $this.funObj().showAuthQR();
                        }, function (dismiss) {});
                    });
                },
                importStudent: function () {
                    // window.top.swal({
                    //     title: '导入excel文件',
                    //     showCancelButton: true,
                    //     cancelButtonText: '取消',
                    //     showLoaderOnConfirm: true,
                    //     allowOutsideClick: true,
                    //     input: 'file',
                    //     inputAttributes: {accept: '.xls,.xlsx'},
                    //     confirmButtonText: '导入',
                    //     preConfirm: function(file) {
                    //         return new Promise(function (resolve, reject) {
                    //             if (!file) {
                    //                 reject('文件不能为空！');
                    //             } else {
                    //                 var fileData = new FormData();
                    //                 fileData.append('file', file);
                    //                 fileData.append('schoolId', $this.params.schoolId);
                    //                 $.ajax({
                    //                     url: baseUrl + 'School/importStudent',
                    //                     type: 'POST',
                    //                     processData: false,
                    //                     contentType: false,
                    //                     data: fileData,
                    //                     complete: function(XMLHttpRequest){
                    //                         var result = XMLHttpRequest.responseJSON;
                    //                         if(xhExtra.checkError(result)) return false;
                    //                         window.top.xhTop.showSuccess(result.msg);
                    //                         $this.dataGrid.reload();
                    //                     }
                    //                 });
                    //             }
                    //         })
                    //     }
                    // });
                    window.top.swal.setDefaults({
                        showCancelButton: true,
                        cancelButtonText: '取消',
                        showLoaderOnConfirm: true,
                        allowOutsideClick: false,
                        progressSteps: ['1', '2', '3']
                    });
                    window.top.swal.queue([
                        {
                            title: '导入excel文件',
                            input: 'file',
                            inputAttributes: {accept: '.xls,.xlsx'},
                            confirmButtonText: '导入',
                            preConfirm: function(file) {
                                return new Promise(function (resolve, reject) {
                                    if (!file) {
                                        reject('文件不能为空！');
                                    } else {
                                        resolve();
                                    }
                                })
                            }
                        },
                        {
                            text: '自动创建班级',
                            input: 'select',
                            inputOptions: {
                                1: '行政班',
                                2: '培优班'
                            },
                            confirmButtonText: '确认',
                            showCancelButton: false
                        },
                        {
                            text: '账号用途',
                            input: 'select',
                            inputOptions: {
                                1: '正式',
                                2: '测试',
                                3: '体验',
                                4: '临时',
                                5: '培训',
                            },
                            confirmButtonText: '确认',
                            showCancelButton: false
                        }
                    ]).then(function(result) {
                        console.log(result);
                        window.top.swal.resetDefaults();
                        var fileData = new FormData();
                        fileData.append('file', result[0]);
                        fileData.append('autoClass', result[1]);
                        fileData.append('type', result[2]);
                        fileData.append('schoolId', $this.params.schoolId);
                        $.ajax({
                            url: baseUrl + 'School/importStudent',
                            type: 'POST',
                            processData: false,
                            contentType: false,
                            data: fileData,
                            complete: function(XMLHttpRequest){
                                var result = XMLHttpRequest.responseJSON;
                                if(xhExtra.checkError(result)) return false;
                                window.top.xhTop.showSuccess(result.msg);
                                $this.dataGrid.reload();
                            }
                        });
                    }, function(dismiss) {window.top.swal.resetDefaults();});
                },
                repairApply: function (level) {
                    var id = $this.dataGrid.getSelectValues('iUserId');
                    var schoolId = $this.params.schoolId;
                    if (id.length === 0 ) {
                        window.top.xhTop.showError('未选中记录！');
                        return false;
                    }else if(id.length > 1){
                        window.top.xhTop.showError('请单选一个学生！');
                        return false;
                    }
                    if (level == 1){
                        window.top.xhTop.showModal({
                            title: '创建设备维修申请单',
                            content: xhTool.getFrameString('device/showCreate', {id:id, schoolId:schoolId}, 470),
                            button: '保存',
                            size: 'sm',
                            width:'600',
                            backClose: false
                        });
                    }else{
                        xhExtra.askChangeStatus('device/delRepairData', {id:id}, $this.dataGrid, '确认取消？');
                    }
                },
                scanLogin: function () {
                    var userId = $this.dataGrid.getSelectValue('iUserId');
                    xhExtra.ajaxRequest('School/getLoginQR', {userId: userId}, {check: true}, function(result) {
                        window.top.swal({
                            title: '登陆-' + $this.dataGrid.getSelectValue('sUserName'),
                            html: '<img src="' + result.msg + '" width="80%">',
                            showConfirmButton: true,
                            confirmButtonText: '确认'
                        }).then(function () {}, function (dismiss) {});
                    });
                },
                addBindTablet: function () {
                    var targetId = $this.dataGrid.getSelectValue('iUserId');
                    if (!targetId) {
                        window.top.xhTop.showError('请选中学生！');
                        return false;
                    }
                    window.top.xhTop.showModal({
                        title: '添加绑定-' + $this.dataGrid.getSelectValue('sUserName'),
                        content: xhTool.getFrameString('School/studBindTablet', {targetId: targetId, schoolId: $this.params.schoolId}, 500),
                        button: '绑定',
                        size: 'md'
                    });
                },
                handBindTablet: function () {
                    var userId = $this.dataGrid.getSelectValue('iUserId');
                    if (!userId) {
                        window.top.xhTop.showError('请选中学生！');
                        return false;
                    }
                    window.top.swal({
                        title: '绑定设备-' + $this.dataGrid.getSelectValue('sUserName'),
                        input: 'text',
                        inputPlaceholder: '设备号',
                        showConfirmButton: true,
                        confirmButtonText: '绑定',
                        showCancelButton: true,
                        cancelButtonText: '取消',
                        preConfirm: function (devNumber) {
                            return new Promise(function (resolve, reject) {
                                if (!devNumber) {
                                    reject('设备号不能为空');
                                }
                                resolve();
                            })
                        }
                    }).then(function (devNumber) {
                        xhExtra.ajaxRequest('school/handBindStudTablet', {userId: userId, devNumber: devNumber}, {success: true, check: true, table: $this.dataGrid});
                    }, function (dismiss) {});
                },
                returnTab:function () {
                    var ids = $this.dataGrid.getSelectValues('iUserId');
                    xhExtra.ajaxRequest('device/ajaxGetPlanName',{schoolId:$this.params.schoolId},{},function (res) {
                        var html = '';
                        html = '<select id="iBPPId" class="form-control">\n' +
                            '                  <option value=""   style="display: none;">请选择一个流程计划</option>\n';
                        if (res.length > 0) {
                            $.each(res, function (index,item) {
                                html += '      <option value="'+item['id']+'" ';
                                html +='>'+item['name']+'</option>\n' ;
                            });
                        }
                        html +='      </select>';
                        window.top.swal({
                            titleText: '退还申请(学生数目:'+ids.length+')',
                            html:html + '<br><textarea type="date" class="form-control" id="mDesc" rows="3"></textarea>',
                            showCancelButton: true,
                            cancelButtonText: '取消',
                            confirmButtonText: '确认',
                            showLoaderOnConfirm: true,
                            preConfirm: function () {
                                return new Promise(function (resolve, reject) {
                                    var desc = $('#mDesc' , window.top.document).val();
                                    var iBPPId = $('#iBPPId',window.top.document).val();
                                    if (!desc || !iBPPId) {
                                        reject('理由必填和流程计划必选');
                                    } else {
                                        resolve(desc);
                                    }
                                })
                            },
                            allowOutsideClick: true
                        }).then(function (desc) {
                            var iBPPId = $('#iBPPId',window.top.document).val();
                            xhExtra.ajaxRequest('device/saveReturnTab',{sSourceIds:ids.join(','),mDesc:desc,iSource:2,iBPPId:iBPPId,iSchoolId:$this.params.schoolId},null,function (res) {
                                window.top.xhTop.showSuccess(res.msg);
                                $this.dataGrid.reload();
                            });
                        }, function(dismiss) {});
                    });
                    // var ids = $this.dataGrid.getSelectValues('iUserId');
                    // window.top.swal({
                    //     titleText: '退还申请(学生数目:'+ids.length+')',
                    //     html:'<textarea type="date" class="form-control" id="mDesc" rows="3"></textarea>',
                    //     showCancelButton: true,
                    //     cancelButtonText: '取消',
                    //     confirmButtonText: '确认',
                    //     showLoaderOnConfirm: true,
                    //     preConfirm: function () {
                    //         return new Promise(function (resolve, reject) {
                    //             var desc = $('#mDesc' , window.top.document).val();
                    //             if (!desc) {
                    //                 reject('理由必填！');
                    //             } else {
                    //                 resolve(desc);
                    //             }
                    //         })
                    //     },
                    //     allowOutsideClick: true
                    // }).then(function (desc) {
                    //     xhExtra.ajaxRequest('device/saveReturnTab',{sSourceIds:ids.join(','),mDesc:desc,iSource:2},null,function (res) {
                    //         window.top.xhTop.showSuccess(res.msg);
                    //         $this.dataGrid.reload();
                    //     });
                    // }, function(dismiss) {});
                },
                setUserName: function () {
                    var userId = $this.dataGrid.getSelectValue('iUserId');
                    if (!userId) {
                        window.top.xhTop.showError('请选中学生！');
                        return false;
                    }
                    window.top.swal({
                        title: '修改姓名-' + $this.dataGrid.getSelectValue('sUserName'),
                        input: 'text',
                        inputPlaceholder: '姓名',
                        showConfirmButton: true,
                        confirmButtonText: '修改',
                        showCancelButton: true,
                        showLoaderOnConfirm: true,
                        cancelButtonText: '取消',
                        preConfirm: function (name) {
                            return new Promise(function (resolve, reject) {
                                if (!name) {
                                    reject('姓名不能为空');
                                }
                                xhExtra.ajaxRequest('school/setUserName', {userId: userId, name: name}, {success: true, check: true, table: $this.dataGrid});
                            })
                        }
                    }).then(function (name) {
                    }, function (dismiss) {});
                },
                setUserSex: function () {
                    var userId = $this.dataGrid.getSelectValue('iUserId');
                    if (!userId) {
                        window.top.xhTop.showError('请选中学生！');
                        return false;
                    }
                    window.top.swal({
                        title: '修改性别-' + $this.dataGrid.getSelectValue('sUserName'),
                        input: 'select',
                        inputOptions: {
                            0: '未知',
                            1: '男',
                            2: '女'
                        },
                        showConfirmButton: true,
                        confirmButtonText: '修改',
                        showCancelButton: true,
                        showLoaderOnConfirm: true,
                        cancelButtonText: '取消',
                        preConfirm: function (sex) {
                            return new Promise(function (resolve, reject) {
                                xhExtra.ajaxRequest('school/setUserSex', {userId: userId, sex: sex}, {success: true, check: true, table: $this.dataGrid});
                            })
                        }
                    }).then(function (name) {
                    }, function (dismiss) {});
                },
                showPayVoucher: function (iUserId) {
                    var userIds = $this.dataGrid.getSelectValues('iUserId');
                    window.top.xhTop.showModal({
                        title: '查看凭证',
                        content: xhTool.getFrameString('school/showPayVoucher', {userIds:userIds}, 350),
                        size: 'lg',
                        width: 800,
                        backClose: false
                    });
                },
                uploadPayVoucher:function(){
                    var userIds = $this.dataGrid.getSelectValues('iUserId');
                    var schoolId = $this.params.schoolId;
                    var url = 'school/uploadPayVoucher?schoolId='+schoolId+'&iId[]=';
                    $.each(userIds, function(index, value) {
                        if (index == 0) {
                            url +=  value;
                        } else {
                            url += '&iId[]=' + value;
                        }
                    });
                    window.top.xhTop.createNewTab('缴费凭证', url, true);
                    // if (userIds.length > 0) {
                    //     window.top.xhTop.createNewTab('上传缴费凭证', url, true);
                    // }

                },
                bindLicence:function () {
                    var sDeviceNumbers = $this.dataGrid.getSelectValues('sDeviceNumber');
                    if (!sDeviceNumbers) {
                        window.top.xhTop.showError('未选中学生！');
                    }
                    var url = 'licence/bindLicence?deviceId[]=';
                    var ifNull = 0;
                    $.each(sDeviceNumbers, function(index, value) {
                        if(value){
                            if (index == 0) {
                                url +=  value;
                            } else {
                                url += '&deviceId[]=' + value;
                            }
                        }else{
                            ifNull = 1;
                        }
                    });
                    if (ifNull == 1) {
                        window.top.xhTop.showError('有选中学生设备号为空！');
                        return false;
                    }
                    window.top.xhTop.showModal({
                        title: '绑定许可证',
                        width: 800,
                        content: '<iframe src="' + url + '"  style="width: 100%;border-style: none;padding: 0px;height: 400px"  scrolling="yes"   ></iframe>',
                        backClose: false
                    });
                },
                setRandomPwd: function () {
                    var ids = $this.dataGrid.getSelectValues('iUserId');
                    if (ids.length <= 0) {
                        window.top.xhTop.showError('未选中记录！');
                        return false;
                    }
                    window.top.swal({
                        title: '设置随机密码-' + ids.length + '人',
                        html: '有效时长：<input type="number" id="random_hour" class="swal2-input" placeholder="默认8小时"><br />' +
                        '随机密码：<input type="password" id="random_pwd" class="swal2-input" placeholder="不填则自动生成" style="max-width: 150px;">',
                        showConfirmButton: true,
                        confirmButtonText: '确认',
                        showCancelButton: true,
                        showLoaderOnConfirm: true,
                        cancelButtonText: '取消',
                        preConfirm: function () {
                            return new Promise(function (resolve, reject) {
                                xhExtra.ajaxRequest('school/setRandomPwd', {
                                    userId: ids,
                                    hour: $('#random_hour', window.top.document).val(),
                                    pwd: $('#random_pwd', window.top.document).val()
                                }, {success: false, check: true}, function (result) {
                                    window.top.swal.close();
                                    $.fileDownload(result.msg, {
                                        failCallback: function (responseHtml, url, error) {
                                            window.top.xhTop.showError('下载失败', error);
                                        }
                                    });
                                });
                            })
                        }
                    }).then(function () {
                    }, function (dismiss) {});
                },
                cleanRandomPwd: function () {
                    var ids = $this.dataGrid.getSelectValues('iUserId');
                    if (ids.length <= 0) {
                        window.top.xhTop.showError('未选中记录！');
                        return false;
                    }
                    xhExtra.ajaxRequest('school/cleanRandomPwd', {userId: ids}, {success: true, check: true});
                },
                useType: function (type) {
                    var ids = $this.dataGrid.getSelectValues('iUserId');
                    if (ids.length <= 0) {
                        window.top.xhTop.showError('未选中用户');
                        return false;
                    }
                    window.top.swal({
                        title: '确定要这么做吗',
                        showCancelButton: true,
                        confirmButtonText: '确认',
                        cancelButtonText: '取消',
                        showLoaderOnConfirm: true,
                        allowOutsideClick: false,
                        preConfirm: function() {
                            return new Promise(function (resolve, reject) {
                                    xhExtra.ajaxRequest(
                                        'School/useType',
                                        {ids: ids, type: type,},
                                        {success: true, table: $this.dataGrid},
                                        function () {
                                            $this.classGrid.reload();
                                        }
                                    );
                                    resolve();
                            })
                        }
                    }).then(function(isConfirm) {}, function(dismiss) {});
                },
                changeSchoolApply: function () {
                    var ids = $this.dataGrid.getSelectValues('iUserId');
                    if (ids.length <= 0) {
                        window.top.xhTop.showError('未选中记录！');
                        return false;
                    }
                    var params = ids.join('_');
                    console.log(params);
                    window.top.xhTop.showModal({
                        title:'申请转校',
                        width:330,
                        content: '<iframe src="'+baseUrl+'School/changeSchool?ids='+params+'"  style="width: 100%;;border-style: none;padding: 0px;height: 300px;"  scrolling="yes" ></iframe>',
                        button:'提交',
                        backClose: false
                    });
                },
                setSignInData: function (type, status) {
                    var ids = $this.dataGrid.getSelectValues('iUserId');
                    if (ids.length <= 0) {
                        window.top.xhTop.showError('未选中记录！');
                        return false;
                    }
                    var arr = $('#list').datagrid('getSelections');
                    var info = [];
                    for(var i=0; i<arr.length; i++){
                        info.push({'userId': arr[i].iUserId, 'deviceNumber': arr[i].sDeviceNumber});
                    }
                    var msg = '';
                    if (type == 1 && status == 1) {
                        msg = '签收设为开启？';
                    }
                    if (type == 1 && status == 0) {
                        msg = '签收设为关闭？';
                    }
                    if (type == 2 && status == 1) {
                        msg = '协议设为开启？';
                    }if (type == 2 && status == 0) {
                        msg = '协议设为关闭？';
                    }
                    if (type == 3 && status == 1) {
                        msg = '配件设为开启？';
                    }
                    if (type == 3 && status == 0) {
                        msg = '配件设为关闭？';
                    }
                    xhExtra.askChangeStatus('School/addSignInData', {info: info, type: type, status:status}, $this.dataGrid, msg);
                },
                userConfigure: function () {
                    var ids = $this.dataGrid.getSelectValues('iUserId');
                    if (ids.length <= 0) {
                        window.top.xhTop.showError('未选中记录！');
                        return false;
                    }
                    window.top.xhTop.showModal({
                        title: '用户功能配置管理',
                        content: xhTool.getFrameString('School/userConfigureList', {ids:ids}, 300),
                        button: '保存',
                        size: 'sm',
                        width:'300',
                        backClose: false
                    });
                },
            }
        }
    }
};
